// server.js
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const routes = require('./routes');
const pool = require('./config/pool'); // 测试数据库连接
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');

dotenv.config();

// 创建写入流
const logStream = fs.createWriteStream(path.join(__dirname, process.env.LOG_FILE), { flags: 'a' });

const app = express();
app.use(cors());
app.use(express.json());
// 向外暴露 uploads 文件夹
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 自定义 morgan 日志格式，记录请求的 IP 地址
morgan.token('ip', (req) => {
    return req.headers['x-forwarded-for'] || req.socket.remoteAddress;
});

// 使用 morgan 记录日志，包括请求的 IP 地址
app.use(morgan('IP :ip - :method :url Code :status Cost :response-time ms - :date[iso] ', { stream: logStream }));

// 测试数据库连接
pool.query('SELECT 1', (err) => {
    if (err) {
        console.error('数据库连接失败:', err);
        return;
    }
    console.log('成功连接到数据库。');
});

app.use('/api', routes);

const PORT = process.env.SERVER_PORT || 3000;
const SERVE = process.env.SERVER_HOST;
app.listen(PORT, () => {
    console.log(`服务器正在运行，端口: ${SERVE}:${PORT}`);
});